package com.ego.cart.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.ego.cart.client.GoodsFeignClient;
import com.ego.cart.interceptor.AuthInterceptor;
import com.ego.cart.pojo.Cart;
import com.ego.cart.properties.JwtProperties;
import com.ego.cart.service.CartService;
import com.ego.common.pojo.JsonUtils;
import com.ego.entity.UserInfo;
import com.ego.exception.enums.ExceptionEnum;
import com.ego.exception.exception.EgoException;
import com.ego.item.entity.Sku;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONUtil;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class CartServiceImpl implements CartService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private GoodsFeignClient goodsFeignClient;


    @Override
    @Transactional
    public void add(Cart cart) {
        try {
            //创建redis操作对象
        HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();
        UserInfo userInfo = AuthInterceptor.getUserInfo();
        String userKey="ego:carts:" + userInfo.getId();
        String skuId =cart.getSkuId().toString();
        Integer num = cart.getNum();
        //先判断redis中是否有这些数据
        Boolean hasKey = hashOperations.hasKey(userKey,skuId);
        if (hasKey){
            //存在的话就将以前的数据进行累加
            String cartJson = (String) hashOperations.get(userKey, skuId);
            //先把字符串转成对象
            cart = JsonUtils.parse(cartJson,Cart.class);
            cart.setNum(cart.getNum()+num);
        }else {
            Sku sku = goodsFeignClient.querySkuBySkuId(cart.getSkuId());
            cart.setPrice(sku.getPrice());
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setTitle(sku.getTitle());
            cart.setImages(sku.getImages());
        }
        //写进redis中
        hashOperations.put(userKey,skuId,JsonUtils.serialize(cart));

        }catch (Exception e){
            EgoException.error(log, ExceptionEnum.CART_ADD_ERROR,e);
        }


    }

    @Override
    public List<Cart> findAll() {
        List<Cart> carts =null;
        try {
            UserInfo userInfo = AuthInterceptor.getUserInfo();
            String userKey="ego:carts:" + userInfo.getId();
            //查询出redis中的数据，将它转成Cart对象并收集起来
            carts=stringRedisTemplate.opsForHash()
                    .values(userKey)
                    .stream()
                    .map(cartJson->JsonUtils.parse(cartJson.toString(),Cart.class)).collect(Collectors.toList());
        }catch (Exception e ){
           e.printStackTrace();

        }
        return carts;
    }

    @Override
    public void updateNum(Long skuId, Integer num) {
        // 获取登录用户
        UserInfo user = AuthInterceptor.getUserInfo();
        String userKey = "ego:carts:" + user.getId();
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(userKey);
        // 获取购物车
        String json = (String)hashOps.get(skuId.toString());
        Cart cart = JsonUtils.parse(json, Cart.class);
        cart.setNum(num);
        // 写入购物车
        hashOps.put(skuId.toString(), JsonUtils.serialize(cart));
    }
}
